package com.carleasoft.mps.adu.business.user.service.impl;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carleasoft.mps.adu.business.basicsInfo.bean.entity.AuthorityUserBasicInfo;
import com.carleasoft.mps.adu.business.basicsInfo.bean.vo.AuthorityUserInfoVo;
import com.carleasoft.mps.adu.business.basicsInfo.bean.vo.UserInfoVos;
import com.carleasoft.mps.adu.business.basicsInfo.dao.AuthorityUserBasicInfoMapper;
import com.carleasoft.mps.adu.business.basicsInfo.excel.ConvertTemplatePath;
import com.carleasoft.mps.adu.business.basicsInfo.excel.ExcelUtils;
import com.carleasoft.mps.adu.business.dept.bean.vo.DeptDetailVo;
import com.carleasoft.mps.adu.business.dept.dao.DeptDao;
import com.carleasoft.mps.adu.business.user.bean.entity.MAuthorityUserDynamic;
import com.carleasoft.mps.adu.business.user.bean.po.MAuthorityUserDynamicPo;
import com.carleasoft.mps.adu.business.user.bean.vo.MAuthorityDeptCountVo;
import com.carleasoft.mps.adu.business.user.bean.vo.MAuthorityUserDynamicExcelVo;
import com.carleasoft.mps.adu.business.user.bean.vo.MAuthorityUserDynamicVo;
import com.carleasoft.mps.adu.business.user.dao.MAuthorityUserDynamicMapper;
import com.carleasoft.mps.adu.common.constants.BusinessErrorEnum;
import com.carleasoft.mps.core.exceptions.BusinessException;
import com.carleasoft.mps.core.user.Constants;
import com.carleasoft.mps.core.user.ThreadUserContext;
import com.carleasoft.mps.core.user.UserCacheData;
import com.carleasoft.mps.core.utils.DateUtil;
import com.carleasoft.mps.core.utils.ExceptionUtil;
import dm.jdbc.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.carleasoft.mps.adu.business.user.service.IMAuthorityUserDynamicService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 人员动态Service业务层处理
 * 
 * @author yiSl
 * @date 2024-04-12
 */
@Service
public class MAuthorityUserDynamicServiceImpl extends ServiceImpl<MAuthorityUserDynamicMapper, MAuthorityUserDynamic> implements IMAuthorityUserDynamicService
{
    @Autowired
    private MAuthorityUserDynamicMapper mAuthorityUserDynamicMapper;

    @Autowired
    private AuthorityUserBasicInfoMapper authorityUserBasicInfoMapper;

    @Autowired
    private DeptDao deptDao;

    /**
     * 查询人员动态
     * 
     * @param id 人员动态主键
     * @return 人员动态
     */
    @Override
    public MAuthorityUserDynamicVo selectMAuthorityUserDynamicById(Integer id)
    {
        return mAuthorityUserDynamicMapper.selectMAuthorityUserDynamicById(id);
    }

    /**
     * 查询人员动态列表
     * 
     * @param mAuthorityUserDynamicPo 人员动态
     * @return 人员动态
     */
    @Override
    public Page<MAuthorityUserDynamicVo> selectMAuthorityUserDynamicList(Page page, MAuthorityUserDynamicPo mAuthorityUserDynamicPo)
    {
        //获取当前用户信息
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        page.setCountId("selectPageCount");
        Page<MAuthorityUserDynamicVo> voPage = new Page<>();
        if (user.getUserCat() == Constants.ORDINARY_USER) {
            if(StringUtils.isEmpty(user.getDeptCode()) ||
                    (StringUtils.isNotEmpty(mAuthorityUserDynamicPo.getDeptCode()) && !mAuthorityUserDynamicPo.getDeptCode().equals(user.getDeptCode()))){
                return new Page<>();
            }
            mAuthorityUserDynamicPo.setDeptCode(user.getDeptCode());
        }
        voPage = mAuthorityUserDynamicMapper.selectMAuthorityUserDynamicList(page,mAuthorityUserDynamicPo);
        if (CollUtil.isNotEmpty(voPage.getRecords())) {
            for (MAuthorityUserDynamicVo record : voPage.getRecords()) {
                if (StringUtils.isNotEmpty(record.getLeaveMsg())) {
                    record.setLeaveMsg(getLeaveMsg(record.getLeaveMsg()));
                }
            }
        }
        return voPage;
    }

    /**
     * 新增人员动态
     * 
     * @param mAuthorityUserDynamic 人员动态
     * @return 结果
     */
    @Override
    public boolean insertMAuthorityUserDynamic(MAuthorityUserDynamic mAuthorityUserDynamic)
    {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        AuthorityUserBasicInfo authorityUserBasicInfo = authorityUserBasicInfoMapper.selectOne(Wrappers.<AuthorityUserBasicInfo>lambdaQuery()
                .eq(AuthorityUserBasicInfo::getUserCode, user.getUserCode()));
        if(authorityUserBasicInfo.getUserSubmitFlag() == 0){
            throw ExceptionUtil.create(BusinessErrorEnum.COUNT_NO_JURISDICTION);
        }
        mAuthorityUserDynamic.setCreatePersonCode(user.getUserCode());
        mAuthorityUserDynamic.setCreatePersonName(user.getUserName());
        mAuthorityUserDynamic.setCreateTime(LocalDateTime.now());
        return this.save(mAuthorityUserDynamic);
    }

    /**
     * 根据部门Code分钟求和当日总条数
     * @return
     */
    @Override
    public List<MAuthorityDeptCountVo> selectMAuthorityDeptCountByDeptCode() {

        return mAuthorityUserDynamicMapper.selectMAuthorityDeptCountByDeptCode(DateUtil.getDate());
    }

    /**
     * 修改人员动态
     * 
     * @param mAuthorityUserDynamic 人员动态
     * @return 结果
     */
    @Override
    public boolean updateMAuthorityUserDynamic(MAuthorityUserDynamic mAuthorityUserDynamic)
    {
        UserCacheData user = ThreadUserContext.getCurrentCacheUser();
        mAuthorityUserDynamic.setUpdatePersonCode(user.getUserCode());
        mAuthorityUserDynamic.setUpdatePersonName(user.getUserName());
        mAuthorityUserDynamic.setUpdateTime(LocalDateTime.now());
        return this.updateById(mAuthorityUserDynamic);
    }
    /**
     * 删除人员动态信息
     * 
     * @param id 人员动态主键
     * @return 结果
     */
    @Override
    public boolean deleteMAuthorityUserDynamicById(Integer id)
    {
        return this.removeById(id);
    }

    @Override
    public boolean userDynamicExcel(MultipartFile file) {
        boolean isOk = false;
        List<MAuthorityUserDynamicExcelVo> list = null;
        try {
            list = ExcelUtils.importExcel(file, MAuthorityUserDynamicExcelVo.class);
            list = list.stream().filter(i -> i.getUserName() != null).collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (CollUtil.isNotEmpty(list)){
            Set<String> userNames = list.stream().map(MAuthorityUserDynamicExcelVo::getUserName).collect(Collectors.toSet());
            List<AuthorityUserInfoVo> userInfoVos = authorityUserBasicInfoMapper.getUserInfoByUserNames(userNames);
            Map<String, AuthorityUserInfoVo> userMap = userInfoVos.stream().collect(Collectors.toMap(AuthorityUserInfoVo::getUserName, Function.identity()));
            //单位信息
            Set<String> deptNames = list.stream().map(MAuthorityUserDynamicExcelVo::getDeptName).collect(Collectors.toSet());
            List<DeptDetailVo> deptInfoVos = deptDao.getDeptInfoByDeptNames(deptNames);
            Map<String, DeptDetailVo> deptMap = deptInfoVos.stream().collect(Collectors.toMap(DeptDetailVo::getDeptName, Function.identity()));
            for (MAuthorityUserDynamicExcelVo dynamicExcelVo : list) {
                DeptDetailVo deptDetailVo = deptMap.get(dynamicExcelVo.getDeptName());
                AuthorityUserInfoVo userInfoVo = userMap.get(dynamicExcelVo.getUserName());
                MAuthorityUserDynamic userDynamic = new MAuthorityUserDynamic();
                userDynamic.setDeptCode(deptDetailVo.getDeptCode());
                userDynamic.setUserCode(userInfoVo.getUserCode());
                userDynamic.setLeaveMsg(getLeaveMsgNum(dynamicExcelVo.getLeaveMsg()));
                userDynamic.setLeaveStartTime(dynamicExcelVo.getLeaveStartTime());
                userDynamic.setLeaveEndTime(dynamicExcelVo.getLeaveEndTime());
                userDynamic.setTelephone(dynamicExcelVo.getTelephone());
                userDynamic.setRemark(dynamicExcelVo.getRemark());
                isOk = this.insertMAuthorityUserDynamic(userDynamic);
            }
        }

        return isOk;
    }

    @Override
    public boolean export(String startTime, HttpServletResponse response){
        MAuthorityUserDynamicPo mAuthorityUserDynamicPo = new MAuthorityUserDynamicPo();
        mAuthorityUserDynamicPo.setSize(9999);
        mAuthorityUserDynamicPo.setStartTime(startTime);
        Page<MAuthorityUserDynamicVo> mAuthorityUserDynamicVos = this.selectMAuthorityUserDynamicList(new Page(mAuthorityUserDynamicPo.getCurrent(), mAuthorityUserDynamicPo.getSize()),mAuthorityUserDynamicPo);
        Map<String, Object> map = new HashMap<>();
        map.put("list", mAuthorityUserDynamicVos.getRecords());
        String path = "\\template\\userDynamicExport.xls";
        TemplateExportParams templatePath = new TemplateExportParams(ConvertTemplatePath.convertTemplatePath(path));
        try {
            ExcelUtils.exportExcel(templatePath, map, "人员动态", response);
        } catch (IOException e) {

        }
        return true;
    }

    public String getLeaveMsg(String leaveMsg){
        String msg = "";
        switch (leaveMsg){
            case "0":
                msg=("借调");
                break;
            case "1":
                msg=("出差");
                break;
            case "2":
                msg=("出院陪护");
                break;
            case "3":
                msg=("休假");
                break;
            case "4":
                msg=("学习");
                break;
            case "5":
                msg=("集训");
                break;
            case "6":
                msg=("其他");
                break;
        }
        return msg;
    }

    public String getLeaveMsgNum(String leaveMsg){
        String msg = "";
        switch (leaveMsg){
            case "借调":
                msg=("0");
                break;
            case "出差":
                msg=("1");
                break;
            case "出院陪护":
                msg=("2");
                break;
            case "休假":
                msg=("3");
                break;
            case "学习":
                msg=("4");
                break;
            case "集训":
                msg=("5");
                break;
            case "其他":
                msg=("6");
                break;
        }
        return msg;
    }
}
